package gappengko;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Utility methods for handling cross-domain requests*/
public class CrossDomainUtils {

	/** sets the Cross-Origin Resource Sharing header
	 * @see http://www.w3.org/TR/cors/
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	public static void enableCrossOriginResourceSharing(HttpServletRequest req, HttpServletResponse res) throws IOException  {

    if (req.getHeader("Origin")!=null) {
      res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));      
    } else {
      res.setHeader("Access-Control-Allow-Origin", "*");		
    }
				
		if (req.getHeader("Access-Control-Request-Method")!=null) {
	    res.setHeader("Access-Control-Allow-Methods", req.getHeader("Access-Control-Request-Method"));		  
		}
		
    if (req.getHeader("Access-Control-Request-Headers")!=null) {
      res.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));      
    }

	}

	/** used by preflight calls from browsers */
	public static void doOptions(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		enableCrossOriginResourceSharing(req, res);
	}

	
}
